<template>
    <view class="gyg-home" :style="{ 'padding-top': commonHeight.navHeight + 'px' }">
        <view v-if="!shownotice" calss="gyg-mian">
            <view class="topBox">
                <view class="workbench-header" :class="{ 'fixtop': setStock }">
                    <!-- 左侧头像和信息 -->
                    <view class="user-info" @click="changeOrg">
                        <image class="avatar" :src="homeImageObj.userImg" mode="widthFix"></image>
                        <view class="greeting">
                            <text class="title">工作台</text>
                            <text class="message">{{ greetingText }}, {{ phoneNumber }}</text>
                        </view>
                        <text v-if="isShowDot" class="dot"></text>
                    </view>
                    <view class="home-scan">
                        <uni-icons type="plus" size="34" color="#2b85e4" @click="callScan"></uni-icons>
                    </view>
                </view>
                <view class="gyg-mian-img">
                    <swiper autoplay interval="3000" indicatorMode="dot" previous-margin="10px" next-margin="10px">
                        <block v-for="(item, i) in imageList" :key="i">
                            <swiper-item>
                                <image class="avatar" :src="item"></image>
                            </swiper-item>
                        </block>
                    </swiper>
                </view>

                <view class="gyg-main-notice">
                    <NoticeScroll class="notice-detail" @showtypeNotice="showtypeNotice" @showdetail="shownoticedetailPage" :noticeList="noticeList1" :interval="5000" lineHeightRatio="2.8" />
                </view>

                <view class="gyg-main-content">
                    <view class="recentUseTitle">最近使用</view>
                    <app-list-new :appRentList="appRentList"></app-list-new>
                    <dataPlane></dataPlane>
                    <view class="gyg-main-list " :class="{ 'listStock': setStock }">
                        <u-tabs v-model="currentTab" @change="handleTabChange" :list="classifyNameArr"
                            :lineWidth="itemWidth" :activeStyle="activeItemStyle" :inactiveStyle="inactiveItemStyle"
                            :itemStyle="listItemStyle">
                        </u-tabs>
                    </view>

                </view>
            </view>
            <view>
                <appCard v-for="(cardItem, cardIndex) in appData" :key="cardItem.classifyId" :cardData="cardItem"
                    @jump="jumpclick" :id="`card${cardIndex}`" class="homeCard" />
            </view>
        </view>
        <view v-if="shownotice">
            <!-- 公告详情 -->
            <notice-detail  v-if="showNoticeDetail" ></notice-detail>
            <notice-list @closeList="closeNoticeList"  v-if="showNoticeType" ></notice-list>
            <!-- 公告列表 -->
        </view>


    </view>
</template>

<script>
// import { tabConfig } from '@/pages/home/comppnents/homeConfig.js'
import noticeList from './components/notice.vue'
import noticeDetail from './components/noticeDetail.vue'
import dataPlane from '../../components/home/dataPlane.vue'
import appListNew from './components/appListNew.vue'
import appCard from '../../components/appCard.vue'
import MeWebView from './components/MeWebView.vue'
import { getAppUrl } from '@/config/server'
import { getQuickAppsKey } from '@/config/server'
import NoticeScroll from './components/NoticeScroll.vue';
export default {
    components: {
        appCard,
        dataPlane,
        MeWebView,
        NoticeScroll,
        appListNew,
        noticeDetail,
        noticeList
    },
    computed: {
        appGroups() {
            return this.$store.state.workbench.appList.filter(v => v.classifyName === '数据仓')
        },
        appUserInfo() {
            return uni.getStorageSync('appUserInfo') ? JSON.parse(uni.getStorageSync('appUserInfo')) : {}
        },
        appRentList() {
            let storedApps = this.$store.state.workbench.quickApps
            console.log('storedApps---', storedApps)
            return storedApps.slice(0, 4)
        },
        // 顶部高度数据
        commonHeight() {
            return this.$store.state.baseData.commonHeight
        },

        appData() {
            let groups = this.$store.state.workbench.appList.filter(v => !['数据仓', '蓝凌OA', '思源OA'].includes(v.classifyName))
            if (this.assetSystemApps.length) {
                groups.push({
                    classifyId: 'assetSystemGroup',
                    classifyName: '资产管理',
                    apps: [...this.assetSystemApps]
                })
            }
            console.log(this.$store.state.workbench.appList,groups, '数据aaa')
            return groups
        },
    },
    data() {
        return {
            text1: ['测试1公告', '测试2紧急公告', '测试3提示'],
            noticeList1: [],
            imageList: [
                `${this.$baseIMGUrl}/static/assets/img/new02.png`,
            ],
            showNoticeDetail: false,
            showNoticeType: false,
            shownotice: false,
            isShowDot: false,
            homeImageObj: {
                userImg: `${this.$baseIMGUrl}/static/assets/img/new01.png`
            },
            assetSystemApps: [],
            showWebView: false,
            webviewStyles: {
                progress: {
                    color: '#FF3333'
                }
            },
            layoutData: [
                { name: '数据', component: 'dataPanel', id: 'dataPanel', visible: true }
            ],
            currentTab: 0,
            inactiveItemStyle: {
            },
            noticeList: [],
            activeItemStyle: {
                color: '#2979ff',
            },
            phoneNumber: uni.getStorageSync('username')|| '', // 手机号
            greetingText: '早上好', // 问候语（早上/下午/晚上好）
            itemWidth: '80',
            setStock: false,
            workorderMenu: {},
            listItemStyle: `positive:relative;margin:0 5px; border-radius: 30px; border: 1px solid #ccc;padding-left: 15px; padding-right: 15px;height: 34px;`,
            listActiveItemStyle: `background: #2979ef;positive:relative;margin:0 5px;color:#fff; border-radius: 30px; border: 1px solid #ccc;padding-left: 15px; padding-right: 15px; height: 34px;`,
            xAccessToken: '',
            totalCount: 0,
            classifyNameArr: [],
            interval: null,

        }
    },
    async onLoad() {
        // this.getNoticeList() // 公告列表
        await this.setGreetingText();
        await this.getWorkorderCode();
        await this.getAppList();
        await this.calculateCount()
        this.$store.dispatch('getMessageTypeList') // 消息列表的type数据
        // 这个接口为什么要调取第三方接口
        // this.$store.dispatch('getWebAppsFlag') // 获取PC端的菜单，是否在




    },
    onShow() {
         // this.getNoticeList() // 公告列表
        // await this.setGreetingText();
        // await this.getWorkorderCode();
        // await this.getAppList();
        // await this.calculateCount()
        // this.$store.dispatch('getMessageTypeList') // 消息列表的type数据s
        // 这个接口为什么要调取第三方接口
        // this.$store.dispatch('getWebAppsFlag') // 获取PC端的菜单，是否在

    },
    methods: {
        closeNoticeList(){
            this.showNoticeType = false;
            this.shownotice = false;
        },
        shownoticedetailPage(){
            // 展示公告详情
            this.shownotice = true;
            this.showNoticeDetail = true;
        },
        showtypeNotice(){
             this.shownotice = true;
            this.showNoticeDetail = false;
            this.showNoticeType = true;
        },
        handleNoticeClick(index) {
            const currentNotice = this.noticeList[index];
            console.log("点击了通知：", currentNotice);
            // 跳转详情页示例
            // uni.navigateTo({
            //     url: `/pages/notice-detail?id=${currentNotice.id}`
            // });
        },
        async getNoticeList() {
            const { memberId, orgId } = uni.getStorageInfoSync('appOrgInfo')
            let resAuth = await this.$Geting(this.$api.getTokenByAppServiceId, { appServiceId: 'fw', orgId, memberId })
            if (resAuth.code === '0') {
                if (resAuth.data.accessToken) {
                    // console.log('有设置Token')
                    this.$store.commit('setNoticeToken', resAuth.data.accessToken)
                }
                let noticeres = this.$Posting(this.$api.noticeList, { pageNum: 1, pageSize: 6, "query": { key: null } }, { 'X-Access-Source': 'roc', 'X-Access-Token': resAuth.data.accessToken || '' })
                if (noticeres.data.code === '0') {
                    this.noticeList = res.data.data.list || [];
                }
                // axios.post(getBaseURL()+this.$api.noticeList, {pageNum:1,pageSize:6,"query": {key: null}},{headers: {'X-Access-Source': 'roc', 'X-Access-Token': resAuth.data.accessToken || ''}}).then(res=>{
                //     console.log('公告--',res.data.data.list);
                //     if(res.data.code==='0'){
                //         this.noticeList = res.data.data.list||[];
                //     }

                // })
            }

        },
        getMenuCode(componentName) {
            if (componentName === 'dataPanel') {
                return this.workorderMenu
            }
            return {}
        },
        createInterval() {
            if (this.interval) {
                clearInterval(this.interval)
            }
            this.interval = setInterval(this.checkLogin, 20 * 1000)
        },
        async calculateCount() {
            this.totalCount = 0
            const url = this.$baseUrl
            await this.getCountOne(url)
            let find = this.appList.find(item => ['LLOA_LLOA', 'OACS_OACS'].includes(item.appCode))
            if (find) {
                await this.getCountTwo(url, find.appCode)
            }
            let todo = this.appList.find(item => item.appCode === 'order_todo_app')
            if (todo) {
                await this.getCountThree(url)
            }
            // if (this.totalCount) {
            //     plus.runtime.setBadgeNumber(this.totalCount);
            // } else {
            //     plus.runtime.setBadgeNumber(0);
            // }
            this.$store.commit("setBadgeNum", this.totalCount);
        },
        async getCountOne(url) {
            console.log('one')
            try {
                const { memberId, orgId } = JSON.parse(uni.getStorageSync('appOrgInfo'))
                let res = await this.$Geting(this.$api.getTokenByAppServiceId, { appServiceId: 'flow_approve', orgId, memberId })
                console.log(res, 'restoken')
                if (res.code === '0') {
                    this.xAccessToken = res.data.accessToken
                    uni.setStorageSync('xAccessToken', this.xAccessToken)
                }
                let params = {
                    pageBean: { page: 1, showTotal: true },
                    query: [],
                }
                let headers = {
                    'X-Access-Source': 'roc',
                    'X-Access-Token': res.data.accessToken || ''
                }
                // let countres = await this.$Posting(this.$api.getShenpiCount, params, headers)
                // console.log(countres, 'shenpi')
                // if (countres) {
                //     const num = countres.data1;
                //     this.totalCount = isNaN(num) ? this.totalCount + 0 : this.totalCount + num
                // }
                // await axios({
                //     method: 'post', url: `${url}${this.$api.getShenpiCount}`, data: { pageBean: { page: 1, showTotal: true }, querys: [] }, headers: 
                // }).then(result => {
                //     const num = result.data.total
                //     this.totalCount = isNaN(num) ? this.totalCount + 0 : this.totalCount + num
                // })
            } catch (error) {

            }
        },
        async getCountTwo(url, appCode) {
            console.log('two')
            const { mobile } = JSON.parse(uni.getStorageSync('appOrgInfo'))
            let result = {}
            if (appCode === 'LLOA_LLOA') {
                // result = await axios({
                //     method: 'post', url: `${url}${this.$api.getLanLingOACount}`, data: { loginName: mobile, types: [0] }, headers: {
                //         'X-Access-Source': 'roc'
                //     }
                // })
            } else if (appCode === 'OACS_OACS') {
                // let startTime = dayjs().startOf('day').valueOf()
                // result = await axios({
                //     method: 'get', url: `${url}${this.$api.getJiZhiOACount}`, params: { userNumber: mobile, startTime }, headers: {
                //         'X-Access-Source': 'roc'
                //     }
                // })
            }
            let resData = result.data
            console.log('调用OA待办数量：' + JSON.stringify(resData))
            if (resData.code === '0') {
                const num = resData.data
                this.totalCount = isNaN(num) ? this.totalCount + 0 : this.totalCount + num
            }
        },
        async getCountThree(url) {
            console.log('three')
            // let appOrgInfo = uni.getStorageSync('appOrgInfo')
            // if (!appOrgInfo) return
            // const { memberId, orgId } = JSON.parse(appOrgInfo)
            // let resOne = await this.$Geting(this.$api.getTokenByAppServiceId, { appServiceId: 'order_todo_app', orgId, memberId })
            // console.log(resOne, 'resone')
            // let token = resOne.data.accessToken
            // await axios({
            //     method: 'post',
            //     url: url + this.$api.getTodoOrderList,
            //     data: {
            //         pageNum: 1,
            //         pageSize: 10,
            //         query: {
            //             deptId: '', // 当前项目节点Id
            //             candidates: this.appUserInfo.memberId || '', // 当前登陆人memberId 必填
            //         }
            //     },
            //     headers: {
            //         'X-Access-Source': 'roc',
            //         'X-Access-Token': token || ''
            //     }
            // }).then((result) => {
            //     const data = +result.data.data.pageDto.total || 0
            //     this.totalCount = this.totalCount + data
            // })
        },
        // 检查当前token是否有效
        async checkLogin() {
            console.log('token')
            if (!this.xAccessToken) {
                return
            }
            // let token = localStorage.XUserToken
            // this.$Posting(this.$api.loginOrg, params)
            // const { data } = await axios.get(`${getBaseURL()}${this.$api.checkLogin}?token=roc-framework-core:roc_auth_token_new_${this.xAccessToken}`)
            const data = await this.$Geting(this.$api.checkLogin, { token: `roc-framework-core:roc_auth_token_new_${this.xAccessToken}` })
            // debugger
            // const _this = this;
            console.log(data, 'data')
            if (data.code === '0') {
                let resData = data.data
                if (resData.code === '-200') {
                    this.removeInterval()
                    this.logout()
                    // uni.showToast({
                    //     icon: 'none',
                    //     title: '登录超时,请重新登录。',
                    // });
                    // setTimeout(() => {
                    //     uni.navigateTo({url: 'pages/login/login'})
                    // }, 300);
                    // this.$message.alert(resData.resultInfo, '提示').then(() => {
                    //     this.logout()
                    // })
                }
            }
        },
        removeInterval() {
            if (this.interval) {
                clearInterval(this.interval)
                this.interval = null
            }
        },
        filterAppGroupList(data) {
            let lanlingFlag = false
            const arr = data.map(item => {
                item.apps.forEach((list, index) => {
                    if (list.h5UrlOld && list.h5UrlOld.includes('roc-component-message-h5')) {
                        item.apps.splice(index, 1)
                    }
                    if (['LLOA_LLOA', 'OACS_OACS'].includes(list.appCode)) {
                        lanlingFlag = true
                    }
                })
                return item
            })
            this.$store.commit('SetIsUsedLanLing', lanlingFlag)
            return arr.filter(item => item.apps.length)
        },
        async getAppList() {
            const appOrgInfo = uni.getStorageSync('appOrgInfo');
            if (!appOrgInfo) {
                console.error('未找到 appOrgInfo 存储数据');
                uni.navigateTo({url: 'pages/login/login'})
                return;
            }
            const { orgId } = JSON.parse(appOrgInfo);
            const baseURL = uni.getStorageSync('baseURL') || '';
            console.log(baseURL, orgId, 'aaa')
            const orgIdBaseURL = orgId + baseURL;

            try {

                const res = await this.$Geting(this.$api.memberAppsInMenuClassfy);
                console.log(res, 'aaa')

                if (res.code === '0') {
                    let apps = [];
                    const resData = this.filterAppGroupList(res.data); // 保留原过滤方法

                    // 3. 处理应用分类和列表数据（逻辑不变）
                    resData.forEach((item, index) => {
                        if (index === 0) {
                            this.classifyNameArr.push({ name: '全部应用' });
                        }
                        apps = apps.concat(item.apps);
                        // 排除指定分类
                        if (!['数据仓', '蓝凌OA', '思源OA'].includes(item.classifyName)) {
                            // this.classifyArr.push(item);
                            this.classifyNameArr.push({ name: item.classifyName });
                        }
                    });
                    this.appList = apps;

                    // 4. 存储默认应用到 Vuex（逻辑不变）
                    if (apps.length) {
                        let find = apps.find(item => item.appCode === 'order_todo_app');
                        if (!find) {
                            find = apps[0];
                        }
                        this.$store.commit('setOrderTodoApp', find);
                    }

                    uni.setStorageSync('appList', JSON.stringify(this.appList));
                    console.log('apps', apps);

                    // // 6. 处理常用应用（逻辑不变，存储API替换）
                    const quickApps_key = getQuickAppsKey(); // 需确保 getQuickAppsKey 方法已适配小程序
                    let storeApps = uni.getStorageSync(quickApps_key) || '';
                    let parseStoreApps = JSON.parse(storeApps || '[]');

                    // // 初始化或过滤常用应用
                    if (!storeApps || storeApps.length === 0) {
                        const filterApps = apps.filter(x => !['LLOA_LLOA', 'OACS_OACS'].includes(x.appCode));
                        parseStoreApps = filterApps.slice(0, 4);
                    } else {
                        // 剔除接口中不存在的应用
                        parseStoreApps = parseStoreApps.filter(x => apps.some(y => y.appCode === x.appCode));
                        // 过滤后无应用时，默认取前4个
                        if (!parseStoreApps.length) {
                            parseStoreApps = apps.slice(0, 4);
                        }
                    }
                    console.log(parseStoreApps, '常用应用')

                    // // 7. 存储常用应用到本地和 Vuex
                    uni.setStorageSync(quickApps_key, JSON.stringify(parseStoreApps));
                    this.$store.commit('setApps', resData);
                    this.$store.commit('setQuickApps', parseStoreApps);
                }
            } catch (err) {
                console.error('获取应用列表失败:', err);
                // 可添加错误提示，如 uni.showToast({ title: '获取应用列表失败', icon: 'none' });
            }
        },
        getWorkorderCode() {
            uni.getStorage({
                key: 'appGroupList',
                success: (res) => {
                    if (res.data) {
                        const data = JSON.parse(res.data);
                        let appList = [];
                        data.forEach((item) => {
                            if (item.appList && item.appList.length) {
                                appList = appList.concat(
                                    item.appList.map(v => ({
                                        ...v,
                                        appCategoryId: item.appCategoryId
                                    }))
                                );
                            }
                        });

                        const list = uni.getStorageSync('appTabList');
                        if (list) {
                            // this.tabList = JSON.parse(list);
                        }
                        const menu = appList.find(ele => ele.appCode === 'order_todo_app');
                        if (menu) {
                            this.workorderMenu = menu;
                            console.log(menu, 'menu')
                        }
                    }
                },
                fail: (err) => {
                    // 处理获取失败（如键不存在）
                    console.error('获取 appGroupList 失败：', err);
                }
            });
        },
        // 调用后端接口退出登录（也即使token失效）
        async makeTokenInvalid() {
            let configs = null
            let res = await this.$Posting(this.$api.memberLogout, {}, true, configs)
            return res
        },
        async logout() {
            // await this.makeTokenInvalid()
            uni.clearStorage();
            this.$store.commit('setAppUserInfo', {}) // 退出登录时清除登录用户在store中的信息
            this.$store.commit('setAppOrgInfo', {})
            this.$store.commit('setAppGroupList', [])
            this.$store.commit('setMessageTypeList', [])
            this.$store.commit('setMessageAccessToken', '')
            this.$store.commit('setFirstShowUpdate', true)
            // this.$router.replace({name: 'login'})
        },
        changeOrg() {
            uni.navigateTo({
                url: 'pages/login/choseOrg'
            })
        },
        // jumpclick(data) {
        //     console.log(data, 'data')
        //     // this.$Router.push({
        //     //     name: 'MeWebView',
        //     //     params: {
        //     //         url: data.h5UrlOld,
        //     //     }
        //     // })
        // },
        // 点击事件处理函数
        jumpclick(app) {
            console.log('点击', app);
            // return
            // 小程序中可通过 debugger 调试，需在开发者工具中开启
            // debugger;

            // 只读状态直接返回
            // if (this.readonly) return;

            const { appCode = '', appCategoryId = '', appServiceId = '', code = '', appId = '', refDevopsAppId = '', orgId = '', appName = '' } = app;
           const h5UrlOld =  app.h5UrlOld ? app.h5UrlOld.trim() : '';
            // 检查网络状态（小程序网络检测）
            // debugger
            uni.getNetworkType({
                success: (res) => {
                    console.log(res, 'res')
                    const isOffline = res.networkType === 'none';
                    // 离线状态且不在白名单内的应用提示网络异常
                    if (isOffline && !['order_draft_app', 'order_todo_app', 'energy_meter_online'].includes(appCode)) {
                        uni.showToast({
                            title: '网络异常，请检查网络',
                            icon: 'none',
                            duration: 2000
                        });
                        return;
                    }

                    // 存储相关参数到本地缓存
                    uni.setStorageSync('workOrderInto', '');
                    uni.setStorageSync('appMenuParams', JSON.stringify({
                        appId: app.appId,
                        refDevopsAppId: app.refDevopsAppId
                    }));
                    uni.setStorageSync('appCategoryId', appCategoryId);

                    // 防止重复点击（3秒内同一链接不重复打开）
                    // if (this.clickedH5UrlOld === h5UrlOld) {
                    //     return;
                    // }
                    // this.clickedH5UrlOld = h5UrlOld;
                    // setTimeout(() => {
                    //     this.clickedH5UrlOld = '';
                    // }, 3000);

                    // 存储当前应用的appCode
                    uni.setStorageSync('currentAppCode', appCode);

                    // // 访客扫码特殊处理
                    // if (appId === '100858') {
                    //     console.log(app.appName);
                    //     uni.navigateTo({
                    //         url: `/pages/visitScanQRRes?code=${encodeURIComponent(app.code)}`
                    //     });
                    //     return;
                    // }

                    // // 访客记录特殊处理
                    // if (appId === '100859' && h5UrlOld) {
                    //     console.log(app.appName);
                    //     this.openWeb(`${h5UrlOld}?code=${app.code}&orgId=${app.orgId}`);
                    //     return;
                    // }

                    // // 访客通行记录特殊处理
                    // if (appId === '100860' && h5UrlOld) {
                    //     console.log(app.appName);
                    //     this.openWeb(`${h5UrlOld}?code=${app.code}&orgId=${app.orgId}`);
                    //     return;
                    // }

                    // 锋物h5应用处理
                    // if (h5UrlOld.includes('aiforward') || h5UrlOld.includes('coscoshipping')) {
                    //     // 云视频和抄表需要先选择项目
                    //     if (/h5\/(video|meter)/i.test(h5UrlOld)) {
                    //         if (!this.ebaProject?.projectId) {
                    //             uni.showToast({
                    //                 title: '请先选择一个项目',
                    //                 icon: 'none',
                    //                 duration: 2000
                    //             });
                    //             return;
                    //         }
                    //     }
                    //     console.log('执行了打开h5');
                    //     this.openFWH5Page(h5UrlOld);
                    //     return;
                    // }

                    // 资产管理系统或蓝凌OA第三方应用处理
                    if (appCategoryId === 'assetSystemGroup' || ['LLOA_LLOA', 'OACS_OACS'].includes(appCode)) {
                        this.openThirdH5Page(app);
                        return;
                    }
                    let token = uni.getStorageSync('XUserToken') || '';
                    // 生成最终打开的URL
                    console.log(h5UrlOld, 'h5url')
                    let localURL = getAppUrl(appCode, code, h5UrlOld ? h5UrlOld.split('#')[1] : '', app, this.appUserInfo) + `&XUserToken=${token}`

                    console.log('===========');
                    console.log(localURL);
                    // return 
                    // 设置订单类型
                    this.setOrderType(appCode);

                    if (localURL) {
                        // 打开新页面（小程序使用navigateTo或web-view）
                        // 这里使用web-view打开H5链接，需在小程序后台配置业务域名
                        // uni.navigateTo({
                        //     url: `/pages/webview?url=${encodeURIComponent(localURL)}`
                        // });
                        this.$Router.push({
                            name: 'MeWebView',
                            params: {
                                url: localURL,
                            }
                        })

                    } else {
                        uni.showToast({
                            title: 'appCode不正确',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                },
                fail: () => {
                    uni.showToast({
                        title: '网络检测失败',
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        },

        // 打开网页的方法（需配合web-view页面）
        openWeb(url) {
            // uni.navigateTo({
            //     url: `/pages/webview?url=${encodeURIComponent(url)}`
            // });
            console.log(url, 'url')
            return
            this.$Router.push({
                name: 'MeWebView',
                params: {
                    url,
                }
            })
        },

        // 锋物H5页面打开方法（根据实际需求实现）
        openFWH5Page(url) {
            // 示例实现：添加锋物H5特有的参数或处理
            const fullUrl = `${url}${url.includes('?') ? '&' : '?'}from=miniprogram`;
            this.openWeb(fullUrl);
        },

        // 第三方H5页面打开方法（根据实际需求实现）
        openThirdH5Page(app) {
            // 示例实现：根据第三方应用特点处理URL
            const { h5UrlOld, code } = app;
            const fullUrl = `${h5UrlOld}${h5UrlOld.includes('?') ? '&' : '?'}code=${code}&from=miniprogram`;
            this.openWeb(fullUrl);
        },

        // // URL生成方法（需要根据实际业务逻辑实现）
        // generateUrl(h5UrlOld, app) {
        //     // 原代码中的URL生成逻辑，需根据实际需求实现
        //     const { code } = app;
        //     return `${h5UrlOld}${h5UrlOld.includes('?') ? '&' : '?'}code=${code}`;
        // },

        // 设置订单类型方法（根据实际需求实现）
        setOrderType(appCode) {
            // 原代码中的订单类型设置逻辑
            // 示例：this.$store.commit('setOrderType', appCode);
        },
        setGreetingText() {
            console.log(this.greetingText, 'gree')
            const hour = new Date().getHours();
            if (hour < 12) {
                this.greetingText = '早上好';
            } else if (hour < 18) {
                this.greetingText = '下午好';
            } else {
                this.greetingText = '晚上好';
            }

        },
        getItemStyle(index) {
            console.log(index, 'aaa')
            return index == currentTab ? listActiveItemStyle : listItemStyle

        },
        toNoticePage(item) {
            console.log(item, 'item')
        },
        handleTabChange(ele) {
            // this.setStock = true;
            this.currentTab = ele.index;
            const query = uni.createSelectorQuery().in(this);
            query.select(`#card${ele.index}`).boundingClientRect(data => {
                if (data) {
                    // console.log(data.top, 'top')
                    uni.pageScrollTo({
                        scrollTop: data.top - 88,
                        duration: 300
                    });
                }
            }).exec();
        },
        // 调起摄像头扫码
        callScan() {
            uni.scanCode({
                // 支持的码格式（默认全支持，可指定特定格式）
                scanType: ['qrCode', 'ean13', 'ean8'],
                // 扫码成功回调
                success: (res) => {
                    console.log('扫码成功', res);
                    //   this.scanResult = `类型：${res.scanType}\n内容：${res.result}`;
                    //   // 扫码结果处理（如跳转页面、解析数据等）
                    //   this.handleScanResult(res.result);
                },
                // 扫码失败回调
                fail: (err) => {
                    console.error('扫码失败', err);
                    uni.showToast({
                        title: '扫码失败，请重试',
                        icon: 'none'
                    });
                }
            });
        }
    }
}
</script>
<style>
.u-tabs__wrapper__nav__line {
    display: none !important;
}
</style>
<style lang="scss" scoped>
.gyg-home {
    width: 100%;
    position: relative;
    // padding-top: 160rpx;
    overflow: hidden;
    background-color: #f5f5f7;
    // min-height: calc(100vh - 160rpx);

    .recentUseTitle {
        margin-bottom: 4px;
        font-size: 16px;
        font-weight: bold;
        color: #333333;
    }

    .gyg-main-notice {
        width: 100%;
        color: #000;
        padding: 0 30rpx;
        box-sizing: border-box;
        background: linear-gradient( 90deg, #FFE1D2 0%, #FFFFFF 100%);
        border-radius: 40rpx;
        // background-color: #fffbe8;
        /* 浅黄背景突出通知 */
        height: 80rpx;
        /* 固定高度，与内容区高度一致 */
        display: flex;
        align-items: center;
        margin-top: 20rpx;
        .notice-detail{
            width: 100vw;
            height: 80rpx;
        }
    }

    .notice-item {
        display: flex;
        align-items: center;
        width: 100%;
        height: 80rpx;
    }

    .notice-icon {
        margin-right: 16rpx;
    }

    .notice-text {
        font-size: 28rpx;
        color: #6b4700;
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .gyg-main-content {
        margin-top: 20rpx;
    }

    // .appcardBox {
    //     border-radius: 40rpx;
    //     margin: 20rpx 32rpx 0;
    //     padding: 20rpx 20rpx;
    //     padding-top: 0.30rpx;
    //     background: #fff;
    // }

    .gyg-main-list {
        margin: 20rpx 0;
        height: 80rpx;
    }

    .topBox {
        padding: 0 30rpx;
        background-color: #fff;
    }

    .gyg-mian {
        position: relative;
        // top: 200rpx;



        .gyg-mian-img {
            width: 100%;
            text-align: center;
            background-color: #ffffff;


            /* 水平居中行内元素 */
            // image {
            //     width: 100%;
            //     display: block;
            //     height: auto;
            //     margin: 0 auto;
            // }
        }

        .gyg-main-content {
            width: 100%;
            // height: 48px;
            margin: 0 auto;
            text-align: center;
            // margin-bottom: 30rpx;



        }
    }

    .homeCard {
        height: auto;
        padding: 30rpx 20rpx;
        // padding-top: 48rpx;
        border-radius: 40rpx;
        // margin-bottom: -20rpx;
    }

    .workbench-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        // padding: 24rpx 30rpx;
        background-color: #ffffff;
        border-bottom: 1rpx solid #f5f5f5;

        // 左侧用户信息
        .user-info {
            display: flex;
            align-items: center;

            // 头像
            .avatar {
                width: 100rpx;
                height: 100rpx;
                border-radius: 50%;
                margin-right: 24rpx;
                background-color: #f0f0f0; // 占位背景
            }

            // 问候语区域
            .greeting {
                display: flex;
                flex-direction: column;
                justify-content: center;

                .title {
                    font-size: 36rpx;
                    font-weight: bold;
                    color: #333333;
                    margin-bottom: 8rpx;
                }

                .message {
                    font-size: 26rpx;
                    color: #666666;
                }
            }
        }

    }

    .gyg-main-content-box {
        margin: 0 auto;
        width: 100%;
        // height: 100px;
        // image{
        //     display: inline-block;
        //     width: 80rpx;
        //     height: 80rpx;
        // }
    }

    .listStock {
        position: fixed;
        top: 310rpx;
        left: 0;
        right: 0;
        z-index: 99;
    }

    .fixtop {
        position: fixed;
        top: 160rpx;
        left: 0;
        right: 0;
        z-index: 99;
    }



    .avatar {
        display: block;
        width: 99%;
        height: 254rpx;
        border-radius: 16rpx;
        padding-top: 20rpx;
        margin: 0 auto;
    }

    .home-scan {
        position: relative;
        // bottom: 100rpx;
        right: 20rpx;
    }
}
</style>